//
//  MYGFriendSearchResultViewController.swift
//  MYDoctor
//
//  Created by 小火科技 on 2024/4/26.
//

import UIKit
import QMUIKit
import MJRefresh

class MYGFriendSearchResultViewController: MYGBaseController {
    private var filterTitle = ""
    var contents: [MYGFriendModel] = []
    private var page = 1
    var hospital = ""
    var department = ""
    var retitle = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
        tableView.mj_header?.beginRefreshing()
    }
    // MARK: - UI
    private func configUI() {
        view.backgroundColor = .white
        
        title = "添加好友"
        view.addSubview(tableView)
        view.addSubview(searchContentView)
        
        searchContentView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(25)
            make.top.equalToSuperview().offset(16)
            make.height.equalTo(28)
        }
        searchContentView.addSubviews([
            searchTextFiled
        ])
        searchTextFiled.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(14)
            make.top.equalToSuperview()
            make.height.equalTo(28)
        }
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(searchTextFiled.snp.bottom).offset(10)
            make.left.right.bottom.equalToSuperview()
        }
        
    }
    private lazy var searchContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .rgba(243, 243, 243)
        view.layerCornerRadius = 14
        view.clipsToBounds = true
        return view
    }()
    
    private lazy var searchTextFiled: QMUITextField = {
        let tf = QMUITextField()
        tf.font = .regular(13)
        tf.textInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
        tf.clearButtonMode = .whileEditing
        let placeholderAtt = NSAttributedString(string: "搜索", attributes: [.foregroundColor: UIColor.rgba(124, 124, 124)]);
        tf.attributedPlaceholder = placeholderAtt;
        let leftImageView = UIImageView(image: UIImage(named: "Chat/search"))
        leftImageView.bounds = CGRect(x: 0, y: 0, width: 15, height: 15)
        tf.leftView = leftImageView
        tf.leftViewMode = .always
        tf.addTarget(self, action: #selector(textFiledEdtingEnded), for: .editingDidEnd)
        tf.addTarget(self, action: #selector(textFiledEdtingEnded), for: .editingDidEndOnExit)
        tf.returnKeyType = .search
        return tf
    }()
    private lazy var tableView: UITableView = {
        let tableV = UITableView()
        tableV.delegate = self
        tableV.dataSource = self
        tableV.separatorStyle = .none
        tableV.register(cellWithClass: MYGAddFriendTableViewCell.self)
        tableV.backgroundColor = .white
        tableV.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.page = 1
            self?.getList()
        })
        
        tableV.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self?.page += 1
            self?.getList()
        })
        return tableV
    }()
    
}

extension MYGFriendSearchResultViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        contents.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        70
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: MYGAddFriendTableViewCell.self, for: indexPath)
        cell.model = contents[indexPath.row]
        cell.isSearch = true
        cell.relaodData = { [self] in
            getList()
        }
        return cell
    }
}

extension MYGFriendSearchResultViewController {
    func getList(){
        MYGLoading.show()
        MMYGNetwork<MYGMessageApi, MYGPageModel<MYGFriendModel>>.request(target:.searchDoctor(kwd: filterTitle, department: self.department, hospital: self.hospital, title: self.retitle,page: self.page)) { [weak self] item in
            MYGLoading.hide()
            guard let item = item else {
                return
            }
            self!.tableView.mj_header?.endRefreshing()
            if item.page.page <= 1 {
                self!.contents = item.list
            } else {
                self!.contents.append(contentsOf: item.list)
            }
            
            if item.page.total <= self!.contents.count {
                self!.tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                self!.tableView.mj_footer?.endRefreshing()
            }
            self!.tableView.reloadData()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    @objc func textFiledEdtingEnded() {
        filterTitle = searchTextFiled.text!
        contents.removeAll()
        //搜索
        getList()
    }
    
    @objc func navigationMoreAction() {
        let vc = MYGMyAnswerViewController()
        self.navigationController?.pushViewController(vc)
    }
}
